import logging
import os
from datetime import datetime


version_info = (0, 1, 1)
versionstr = '.'.join(map(str, version_info))

class CusLog:
	def __init__(self, log_type='mylog', bottomlevel=logging.DEBUG, displaylevel=logging.INFO, filelevel=logging.DEBUG, log_path='./logs/'):
		self.logger = logging.getLogger(log_type)
		self.logger.setLevel(bottomlevel)
		if(not os.path.exists(log_path)):
			os.makedirs(log_path)
		
		self.log_file = os.path.join(log_path, f"{log_type}_{datetime.now().strftime('%Y%m%d')}.log")
		# Create file handler which logs even debug messages
		self.fh = logging.FileHandler(self.log_file)
		#self.fh.setLevel(level)
		self.fh.setLevel(filelevel)
		
		# Create console handler with a higher log level
		self.ch = logging.StreamHandler()
		self.ch.setLevel(displaylevel)
		
		# Create formatter and add it to the handlers
		self.formatter = logging.Formatter('[%(asctime)s][' + log_type + '][%(levelname)s][%(message)s]', datefmt='%Y%m%d %H:%M:%S')
		#self.formatter = logging.Formatter('[%(asctime)s][%(levelname)s] - %(message)s', datefmt='%Y%m%d %H:%M:%S')
		self.fh.setFormatter(self.formatter)
		self.ch.setFormatter(self.formatter)
		
		# Add the handlers to the logger
		self.logger.addHandler(self.fh)
		self.logger.addHandler(self.ch)

	def cusinfo(self, message, detail=None):
		currmsg = f"[{message}][{detail}]" if detail else f"[{message}]"
		self.logger.info(currmsg)
	
	def cusdebug(self, message, detail=None):
		currmsg = f"[{message}][{detail}]" if detail else f"[{message}]"
		self.logger.debug(currmsg)

	def cuserror(self, message, detail=None):
		currmsg = f"[{message}][{detail}]" if detail else f"[{message}]"
		self.logger.error(currmsg)

	def clear_handlers(self):
		self.logger.removeHandler(self.fh)
		self.logger.removeHandler(self.ch)
		self.fh.close()
		self.ch.close()

if __name__ == '__main__':
	import sys
	if (sys.argv[1] == '-v'):
		scriptname = os.path.basename(__file__)
		print(f"{scriptname}:{versionstr}")
		sys.exit(0)


	#test code
	cuslog = CusLog(log_type='testlog')
	cuslog.cusinfo("This is an info message", detail="Additional details here")
	cuslog.cusinfo("This is another info message without details")
	cuslog.cusdebug("This is a debug info message", detail="Additional details here")
	cuslog.cusdebug("This is another debug info message without details")